<style>
    ul.ztree {margin-top: 10px;border: 1px solid #617775;background: #f0f6e4;width:220px;overflow-y:scroll;overflow-x:auto;}
</style>

<article class="page-container">
    <form action="" method="post" class="form form-horizontal" id="form-article-add" enctype="multipart/form-data">
        <div class="row cl">
            <label for="articletitle" class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>文章标题：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <input type="text" class="input-text" id="articletitle" name="title" value="{$detail['title']}">
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>分类栏目：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <!-- 树插件 start -->
                <input type="text" class="input-text" id="citySel" name="articlecategory" value="{$detail['category']['name']}" placeholder="请选择！" onclick="showMenu(); return false;" readonly>
                <input type="hidden" name="category_id" value="{$detail['category']['id']}">
                <div id="menuContent" class="menuContent" style="display:none; position: fixed;z-index: 15;">
                    <ul id="treeDemo" class="ztree" style="margin-top:0; width:160px;"></ul>
                </div>
                <!-- 树插件 end -->
            </div>
        </div>
        <div class="row cl">
            <label for="articlesort" class="form-label col-xs-4 col-sm-2">排序值：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <input type="text" class="input-text" id="articlesort" name="articlesort" value="{$detail['sort']}">
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">关键词：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <input type="text" class="input-text" value="" placeholder="" id="keywords" name="keywords">
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">文章摘要：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <textarea name="abstract" class="textarea"  placeholder="说点什么...最少输入10个字符" datatype="*10-100" dragonfly="true" onKeyUp="$.Huitextarealength(this,200)"></textarea>
                <p class="textarea-numberbar"><em class="textarea-length">0</em>/200</p>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">允许评论：</label>
            <div class="formControls col-xs-8 col-sm-9 skin-minimal">
                <div class="check-box">
                    <input type="checkbox" id="allowcomments" name="allowcomments" checked="checked">
                    <label for="checkbox-pinglun">&nbsp;</label>
                </div>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">封面图：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <!-- 文件上传 start -->
                <div class="uploader-thum-container">
                    <div id="fileList" class="uploader-list"><img src="{:config('upload_path')}/{$detail['cover']}" style="height: 100px;"></div>
                    <div id="filePicker">选择图片</div>
                </div>
                <!-- 文件上传 end -->
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">文章内容：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <script id="editor" type="text/plain" name="description">{$detail['description']|raw}</script>
            </div>
        </div>
        <div class="row cl">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2">
                <button class="btn btn-primary radius js_btn_submit" type="button"><i class="Hui-iconfont">&#xe632;</i> 保存</button>
                <button onClick="removeIframe();" class="btn btn-default radius" type="button">&nbsp;&nbsp;取消&nbsp;&nbsp;</button>
            </div>
        </div>
    </form>
</article>

<!--请在下方写此页面业务相关的脚本-->
<script src="/admin/lib/My97DatePicker/4.8/WdatePicker.js"></script>
<script src="/admin/lib/jquery.validation/1.14.0/jquery.validate.js"></script>
<script src="/admin/lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script src="/admin/lib/jquery.validation/1.14.0/messages_zh.js"></script>
<script src="/admin/lib/webuploader/0.1.5/webuploader.min.js"></script>
<script src="/admin/lib/ueditor/1.4.3/ueditor.config.js"></script>
<script src="/admin/lib/ueditor/1.4.3/ueditor.all.min.js"> </script>
<script src="/admin/lib/ueditor/1.4.3/lang/zh-cn/zh-cn.js"></script>
<script src="/admin/lib/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script>
<link rel="stylesheet" href="/admin/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css">
<script>
    /* 树插件-回调函数 start */
    function onClick(e, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj('treeDemo'),
            nodes = zTree.getSelectedNodes(),
            nodeId = '',
            nodeName = '';
        //排序
        nodes.sort(function compare(a,b){return a.id-b.id;});
        //遍历（多选的）节点
        for (var i=0, l=nodes.length; i<l; i++) {
            nodeId += nodes[i].id + ',';
            nodeName += nodes[i].name + ',';
        }
        if (nodeId.length > 0 ){
            nodeId = nodeId.substring(0, nodeId.length-1);
            nodeName = nodeName.substring(0, nodeName.length-1);
        }
        $('[name="category_id"]').attr('value', nodeId);
        $("#citySel").attr("value", nodeName);
    }

    function showMenu() {
        var cityObj = $("#citySel");
        var cityOffset = cityObj.offset();
        $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");

        $("body").bind("mousedown", onBodyDown);
    }
    function hideMenu() {
        $("#menuContent").fadeOut("fast");
        $("body").unbind("mousedown", onBodyDown);
    }
    function onBodyDown(event) {
        if (!(event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
            hideMenu();
        }
    }
    /* 树插件-回调函数 end */
    $(function(){
        //表单美化插件
        $('.skin-minimal input').iCheck({
            checkboxClass: 'icheckbox-blue',
            radioClass: 'iradio-blue',
            increaseArea: '20%'
        });

        //树插件
        // zTree 的参数配置
        var setting = {
            view: {
                dblClickExpand: false,
                //禁止多选
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'pid',//父级id的键
                    rootPId: null //（根节点）父级id的值
                }
            },
            callback: {
                onClick: onClick
            }
        };
        //ajax获取分类列表
        $.ajax({
            url: '/index.php/admin/category/getList',
            success: function(response){
                if (response.code == '1') {
                    //获取成功
                    var zTree = $.fn.zTree.init($('#treeDemo'), setting, response.data);//实例化zTree
                    var nodes = zTree.getNodes();
                    if (nodes.length>0) {
                        zTree.expandNode(nodes[nodes.length-1], true, true, true);//展开最后一个根节点（包括其全部子节点）
                    }
                }else{
                    layer.msg('无法获取分类列表，请刷新。', {icon:0,time:3000});
                }
            },
            error: function(data){
                layer.msg('发送失败!',{icon:0,time:3000});
            }
        });

        //图片上传插件
        var $list = $("#fileList");
        // 优化retina, 在retina下这个值是2
        var ratio = window.devicePixelRatio || 1;
        var thumbnailWidth = 100 * ratio;//预览图的宽高px（当取值为[0,1]时，表示百分比）
        var thumbnailHeight = 100 * ratio;

        //初始化 WebUploader
        var uploader = WebUploader.create({
            //自动上传
            auto: false,
            swf: 'lib/webuploader/0.1.5/Uploader.swf',
            // 文件接收服务端。
            server: 'fileupload.php',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#filePicker',
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
            }
        });
        // 当文件被加入队列之前触发
        uploader.on('beforeFileQueued', function(file){
            uploader.reset();//清空上传队列
            $list.empty();
        });
        // 当有文件添加进来的时候-创建图片预览
        uploader.on( 'fileQueued', function( file ) {
            var $li = $(
                '<div id="' + file.id + '" class="item">' +
                '<div class="pic-box"><img></div>'+
                '<div class="info">' + file.name + '</div>' +
                '</div>'
            );
            var $img = $li.find('img');
            //追加到预览列表
            $list.append( $li );

            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            uploader.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }

                $img.attr( 'src', src );
            }, thumbnailWidth, thumbnailHeight );
        });

        //编辑器插件
        var ue = UE.getEditor('editor');

        //表单验证插件
        var validator = $("#form-article-add").validate({
            rules:{
                articletitle:{
                    required:true
                },
                articlecategory:{
                    required:true
                }

            }
        });
        //点击提交表单
        $(document).on('click', '.js_btn_submit', function(event){
            var form = $(this).parents('form');
            var formData = new FormData(form[0]);
            var files = uploader.getFiles();
            if (files.length > 0) {
                formData.append('cover', files[0].getSource().getSource());
            }
            //判断
            if (!validator.form()) {
                return false;
            }
            //ajax提交表单
            $.ajax({
                type: $(form).attr('method'),
                url: $(form).attr('action'),
                data: formData,
                processData: false,
                contentType: false,
                success: function(response){
                    if (response.code == 1) {
                        layer.msg('操作成功!',{icon:1,time:1000},function(){
                            //这里关闭（避免ajax还没发送出去就关闭了iframe框架）
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        });
                    }else{
                        layer.msg(response.msg, {icon:0,time:3000});
                    }
                },
                error: function(xhr, textStatus, errorThrown){
                    layer.msg('发送失败!',{icon:0,time:3000});
                }
            });

        });
    });
</script>
<!--/请在上方写此页面业务相关的脚本-->